package com.hk.servlet;

import com.alibaba.fastjson.JSONObject;
import com.hk.model.News;
import com.hk.model.NewsType;
import com.hk.model.vo.ResultVO;
import com.hk.service.INewsService;
import com.hk.service.INewsTypeService;
import com.hk.service.impl.NewsServiceImpl;
import com.hk.service.impl.NewsTypeServiceImpl;
import com.hk.utils.CharacterEncoding;
import com.hk.utils.Tool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Author: KangWang
 * Date: 2021/5/17 10:20
 * State：Servlet 数据请求转发 控制层
 */
@WebServlet("/newsTrends")
public class NewsTrendsServlet extends HttpServlet {

    /**
     * 查询所有新闻或通过新闻类型查询所属新闻
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        统一字符编码
        CharacterEncoding.setCharacterEncodingResp(req,resp,"UTF-8");
        INewsService iNewsService = new NewsServiceImpl();
        String page = Tool.nullToString(req.getParameter("page"));
        String limit = Tool.nullToString(req.getParameter("limit"));
        String id = Tool.nullToString(req.getParameter("typeId"));
        int i = Tool.parseInt(page);
        int size = Tool.parseInt(limit);
        int typeId = Tool.parseInt(id);
        //        根据sql语句规则将每页页码修改为需要数值
        int pageNum = Tool.pageNum(i,size);
        List<News> newsList = iNewsService.findAll(pageNum, size, typeId);
//         总数
        int count = iNewsService.count(-1, -1, typeId);
        ResultVO<News> resultVO = new ResultVO<News>();
        PrintWriter out = resp.getWriter();
        if (!newsList.isEmpty()) {
            resultVO.setStatus(1);
            resultVO.setMessage("success");
            resultVO.setPageNum(i);
//            总页数
            int pages = Tool.pageSize(size, count);
            resultVO.setPages(pages);
            resultVO.setTotal(newsList.size());
            resultVO.setList(newsList);
        } else {
            resultVO.setStatus(0);
            resultVO.setMessage("error");
            resultVO.setPageNum(i);
            resultVO.setPages(0);
            resultVO.setTotal(newsList.size());
            resultVO.setList(newsList);
        }
        String resultVOJSON = JSONObject.toJSONString(resultVO);
        out.write(resultVOJSON);
        out.flush();
        out.close();

    }

}
